package com.runyu.cordova.plugin;

import android.content.Context;

import java.security.KeyPair;
import java.security.PublicKey;
import java.util.UUID;

public class DeviceManager {
    public static final String INIT_FLAG = "init";
    private static volatile DeviceManager instance;
    public static DeviceManager getInstance() {
        if (instance == null) {
            synchronized (DeviceManager.class) {
                if (instance == null) {
                    instance = new DeviceManager();
                }
            }
        }
        return instance;
    }

    public synchronized void init(Context context){
        if(this.isDeviceReady(context)){
            return;
        }
        try {
            createDeviceId(context);
            AppPreferences.save2Preferences(context, AppPreferences.KEY_INIT, INIT_FLAG);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isDeviceReady(Context context){
        String initFlag = AppPreferences.getFromPreferences(context, AppPreferences.KEY_INIT);
        return INIT_FLAG.equals(initFlag);
    }

    private void createDeviceId(Context context) throws Exception {
        KeyStoreHelper.generateKeyPair(context);
        String uuid = UUID.randomUUID().toString();
        KeyPair keyPair = KeyStoreHelper.getKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        String encryptedUUID = EncryptionHelper.encryptData(uuid, publicKey);
        AppPreferences.save2Preferences(context, AppPreferences.KEY_ENCRYPTED_DEVICE_ID, encryptedUUID);
    }

    public String getSerialNumber(Context context){
        String encryptedUuid = AppPreferences.getFromPreferences(context, AppPreferences.KEY_ENCRYPTED_DEVICE_ID);
            try {
                KeyPair keyPair = KeyStoreHelper.getKeyPair();
                return EncryptionHelper.decryptData(encryptedUuid, keyPair.getPrivate());
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
    }
}
